<?php

namespace App\Exceptions;

use Illuminate\Database\Eloquent\ModelNotFoundException;
use Psr\Log\LoggerInterface;
use Spatie\Permission\Exceptions\UnauthorizedException;
use Symfony\Component\HttpKernel\Exception\NotFoundHttpException;
use Symfony\Component\HttpKernel\Exception\UnauthorizedHttpException;
use Throwable;
use App\Models\Common\ApiResponse;
use Illuminate\Auth\AuthenticationException;
use Tymon\JWTAuth\Exceptions\TokenInvalidException;
use Illuminate\Foundation\Exceptions\Handler as ExceptionHandler;

class Handler extends ExceptionHandler
{
    /**
     * A list of the exception types that are not reported.
     *
     * @var array<int, class-string<Throwable>>
     */
    protected $dontReport = [
        \InvalidArgumentException::class,
        DeviceClientException::class
    ];

    /**
     * A list of the inputs that are never flashed for validation exceptions.
     *
     * @var array<int, string>
     */
    protected $dontFlash = [
        'current_password',
        'password',
        'password_confirmation',
    ];

    /**
     * Register the exception handling callbacks for the application.
     *
     * @return void
     */
    public function register()
    {
        $this->reportable(function (Throwable $e) {
            //
        });
    }

    public function render($request, Throwable $e)
    {
        switch (get_class($e)) {
            case AuthenticationException::class:
            case TokenInvalidException::class:
            case UnauthorizedHttpException::class:
                $respMsg = '身份令牌认证失败,请重新登录';
                $respCode = ApiResponse::RESP_CODE_UNAUTHENTICATED;
                break;
            case ModelNotFoundException::class:
                $respCode = ApiResponse::RESP_CODE_FAILURE;
                $respMsg = '系统中未查到到匹配的数据,请确认参数是否正确';
                break;
            case NotFoundHttpException::class:
                $respCode = ApiResponse::RESP_CODE_FAILURE;
                $respMsg = '未匹配到系统对应的接口路由,请确认请求Url是否正确';
                break;
            case UnauthorizedException::class:
                $respCode = ApiResponse::RESP_CODE_AUTHORIZATION;
                $respMsg = '请求鉴权失败';
                break;
            case \InvalidArgumentException::class:
            case DeviceClientException::class:
                $respCode = $e->getCode() ?: ApiResponse::RESP_CODE_FAILURE;
                $respMsg = $e->getMessage();
                break;
            default:
                $respCode = ApiResponse::RESP_CODE_FAILURE;
                $respMsg = $e->getMessage();
                break;
        }

//        app(LoggerInterface::class)->error($e->getMessage(), ['file' => $e->getFile()]);

        return response()->json(ApiResponse::return($respMsg, null, $respCode), 200, [], 256);
    }
}
